package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.audit.baidu.BaiduImageScan;
import com.heima.audit.baidu.BaiduTextScan;
import com.heima.audit.tess4j.Tess4jClient;
import com.heima.feign.ApArticleFeignClient;
import com.heima.file.service.impl.MinIOFileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.*;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.beans.Transient;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

     @Autowired
    private WmNewsMaterialService wmNewsMaterialService;
     @Autowired
    private WmMaterialService wmMaterialService;
     @Autowired
    private BaiduTextScan baiduTextScan;
     @Autowired
    private BaiduImageScan baiduImageScan;
     @Autowired
    private MinIOFileStorageService minIOFileStorageService;
     @Autowired
    private WmUserService userService;
     @Autowired
    private WmChannelService channelService;
     @Autowired
    private ApArticleFeignClient articleFeignClient;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private Tess4jClient tess4jClient;


    /**
     * 查询自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newList(WmNewsPageReqDto dto) {
        WmUser user = WmThreadLocalUtil.getUser();
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(user.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        dto.checkParam();
        Page page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> lqw = Wrappers.<WmNews>lambdaQuery();
        lqw.eq(WmNews::getUserId,user.getId());
        if(dto.getStatus() != null){
            lqw.eq(WmNews::getStatus,dto.getStatus());
        }
        if(dto.getChannelId() != null){
            lqw.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if(!StringUtils.isBlank(dto.getKeyword())){
            lqw.like(WmNews::getTitle,dto.getKeyword());
        }

        if(dto.getBeginPubdate() != null && dto.getEndPubdate()!=null){
           lqw.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }
        page(page, lqw);

        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());

        result.setData(page.getRecords());

        return result;
    }

    /**
     * 发布
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submit(WmNewsDto dto) {

        if(StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getType()==-1){
            dto.setType(null);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //封装images到wmnews实体中
        List<String> images = dto.getImages();
        //把转成字符串
        if(images!=null && images.size()>0){
            //利用工具类把集合转化成字符串，并且每个之间用逗号间隔
            String imgStr = StringUtils.join(images, ",");
            wmNews.setImages(imgStr);
        }

        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        if(dto.getId()==null){
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        }else{
            wmNewsMaterialService.remove(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }

        if(dto.getStatus()==0){
            return ResponseResult.okResult(null);
        }

        //关联内容图片和素材库

        List<Object> contentImages = getImages(dto);
        getWmMaterials(contentImages, wmNews,0);

        //关联标题图片和素材库
        List<String> titleImages = dto.getImages();
        if(dto.getType()== null){
            List<String> images1 = (List)getImages(dto);
            int size = images1.size();
            if(size>=1&&size<3){
                titleImages= images1.stream().limit(1).collect(Collectors.toList());
                wmNews.setType((short) 1);
            }else if(size>=3){
                titleImages= images1.stream().limit(3).collect(Collectors.toList());
                wmNews.setType((short) 3);
            }else{
                wmNews.setType((short) 0);
            }
            if(titleImages.size()>0) {
                wmNews.setImages(StringUtils.join(titleImages, ","));
            }
        }
        updateById(wmNews);
        getWmMaterials(titleImages, wmNews,1);
        autoScanWmNews(wmNews.getId());
        return ResponseResult.okResult("操作成功");
    }

    /**
     * 审核文章
     *
     * @param id
     */
    @Override
    @Transactional
    @Async
    public void autoScanWmNews(Integer id) {
        WmNews wmNews = getById(id);
        if(wmNews.getContent()==null){
            return;
        }
        String content = wmNews.getContent();
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        StringBuilder strText = new StringBuilder();
        StringBuilder strImages = new StringBuilder();
        //获取标题文本
        if(wmNews.getTitle() != null) {
            String title = wmNews.getTitle();
            strText.append(title);
        }
        //获取标题图片
        if(wmNews.getImages() != null) {
            String images = wmNews.getImages();
            strImages.append(images).append(",");
        }
        //获取content中的文本
        maps.stream().filter(s -> s.get("type").equals("text")).forEach(s->{
            if(s.size()>0) {
                strText.append(s.get("value"));
            }
        });
        //判断是否有本地违禁字
        boolean isSensitive = handleSensitiveScan(strText.toString(), wmNews);
        if(!isSensitive) {return;}
        //获取images中的图片
        maps.stream().filter(s -> s.get("type").equals("image")).forEach(s->{
            if(s.size()>0) {
                strImages.append(s.get("value")).append(",");
            }
        });
        //审核文本
        Integer testStatus = baiduTextScan.textScan(strText.toString());
        if(testStatus==2){
            //修改wm_news表
            updateWmNews(wmNews, (short) 2, "文本中可能包含不合规的内容");
            return;
        }else if(testStatus==3){
            //修改wm_news表
            updateWmNews(wmNews, (short) 3, "文本中可能包含疑似不合规的内容,请通过人工审核");
            return ;
        }else if(testStatus==4){
            //修改wm_news表
            updateWmNews(wmNews, (short) 2, "文本中可能包含审核失败的内容");
            return ;
        }

        //审核图片
        List<String> collect = Arrays.stream(strImages.toString().split(",")).filter(s->!s.isEmpty()).distinct().collect(Collectors.toList());
        if(collect.size() > 0){
            boolean flag = true;
            for (String image : collect) {
                byte[] bytes = minIOFileStorageService.downLoadFile(image);
                Integer status = baiduImageScan.imageScan(bytes);
                if(status==2){
                    //修改wm_news表
                    updateWmNews(wmNews, (short) 2, "图片中可能包含不合规的内容");
                    flag = false;
                    break;
                }else if(status==3){
                    //修改wm_news表
                    updateWmNews(wmNews, (short) 3, "图片中可能包含疑似不合规的内容,请通过人工审核");
                    flag = false;
                    break;
                }else if(status==4){
                    //修改wm_news表
                    updateWmNews(wmNews, (short) 2, "图片中可能包含审核失败的内容");
                    flag = false;
                    break;
                }


                try {

                    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                    BufferedImage imageByte= ImageIO.read(in);
                    String result = tess4jClient.doOCR(imageByte);
                    boolean isImages = handleSensitiveScan(result, wmNews);
                    if(!isImages) {
                        flag = isImages;
                        return;}
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            if(!flag){
                return;
            }
        }
        //保存前端文章三剑客
        ResponseResult result = saveArticle(wmNews);

        if(result.getCode().equals(200)){
            wmNews.setArticleId(Long.valueOf(result.getData().toString()));
            updateWmNews(wmNews, (short) 9,"审核发布成功");
        }
    }

    /**
     * 保存前端文章三剑客
     * @param wmNews
     * @return
     */
    private ResponseResult saveArticle(WmNews wmNews) {
        ArticleDto dto=new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setAuthorId(wmNews.getUserId());
        WmUser user = userService.getById(wmNews.getUserId());
        dto.setAuthorName(user.getName());
        dto.setChannelId(dto.getChannelId());
        WmChannel channel = channelService.getById(dto.getChannelId());
        dto.setChannelName(channel.getName());
        dto.setLayout(wmNews.getType().intValue());
        //创建时间
        dto.setCreatedTime(new Date());

        //设置行为数量默认为0
        dto.setViews(0);
        dto.setLikes(0);
        dto.setComment(0);
        dto.setCollection(0);

        ResponseResult result = articleFeignClient.save(dto);
        return result;
    }

    private boolean handleSensitiveScan(String context, WmNews wmNews) {
        boolean flag = true;
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        List<String> collect = wmSensitives.stream().map(s -> s.getSensitives()).collect(Collectors.toList());
        SensitiveWordUtil.initMap(collect);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(context);
        if(map.size() >0){
            updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews,short status,String str) {
        wmNews.setStatus(status);
        wmNews.setReason(str);
        updateById(wmNews);
    }

    private List<Object> getImages(WmNewsDto dto) {
        List<Map> maps = JSONArray.parseArray(dto.getContent(), Map.class);
        List<Object> contentImages =  maps.stream().filter(s->s.get("type").equals("image")).map(s -> s.get("value")).collect(Collectors.toList());
        return contentImages;
    }

    private void getWmMaterials(List images, WmNews wmNews,int type) {
        if(images.size()<=0){
            return;
        }
        List<WmMaterial> list = wmMaterialService.list(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
        list.forEach(s->{
            int i = 0;
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(s.getId());
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setType((short)type);
            wmNewsMaterial.setOrd((short)i);
            i++;
            wmNewsMaterialService.save(wmNewsMaterial);
        });
    }
}
